<template>
  <div class="hView">
    <header-bar tittle="编辑任务" />

    <div class="bg"></div>

    <div class="card">
      <div class="form">
        <van-form @submit="onSubmit">
          <van-field
            readonly
            clickable
            label-align="center"
            style="font-size: 16px"
            label-width="4.5rem"
            label="任务类型"
            :value="checkName"
            placeholder="任务类型"
            @click="showPicker1 = true"
          />
          <van-popup v-model="showPicker1" round position="bottom">
            <van-picker
              title="任务类型"
              show-toolbar
              :columns="list"
              @cancel="showPicker1 = false"
              @confirm="onConfirm1"
            />
          </van-popup>
          <van-field
            label-align="center"
            label-width="4.5rem"
            v-model="name"
            type="text"
            size="large"
            name="name"
            label="任务名称"
            placeholder="任务名称"
            :rules="getRule(name)"
            style="font-size: 16px"
          />
          <van-field
            label-align="center"
            label-width="4.5rem"
            v-model="taskLink"
            type="text"
            size="large"
            name="taskLink"
            label="任务链接"
            placeholder="任务链接"
            :rules="[{ required: true, message: '请填写任务链接' }]"
            style="font-size: 16px"
          />
          <van-field
            label-align="center"
            label-width="4.5rem"
            size="large"
            v-model="requirement"
            type="text"
            name="requirement"
            label="需求说明"
            placeholder="需求说明"
            :rules="[{ required: true, message: '请填写任务价格' }]"
            style="font-size: 16px"
          />
          <van-field
            readonly
            clickable
            label-align="center"
            style="font-size: 16px"
            label-width="4.5rem"
            label="有效时间"
            :value="value"
            placeholder="有效时间"
            @click="showPicker = true"
            :rules="[{ required: true, message: '请选择有效时间' }]"
          />
          <van-popup v-model="showPicker" round position="bottom">
            <van-picker
              title="有效时间"
              show-toolbar
              :columns="columns"
              @cancel="showPicker = false"
              @confirm="onConfirm"
            />
          </van-popup>
          <div class="upload">
            <div class="headerUp">修改验证图</div>
            <div class="uploadCo">
              <van-uploader
                :before-read="beforeRead"
                v-model="fileList"
                multiple
                :max-count="1"
              />
            </div>
          </div>

          <!-- <div style="margin: 16px">
            <van-button
              round
              block
              type="info"
              color="#f95d4d"
              native-type="submit"
              >保存</van-button
            >
          </div> -->
        </van-form>
      </div>
    </div>

    <div class="btn-box">
      <div class="btn u-flex-center" @click="onSubmit()">保存修改</div>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import { Image as VanImage } from "vant";
import axios from "axios";
import { API_PATH } from "@/api/index.js";
import { getLocalStorage } from "@/util/local-storge.js";
import {
  TASK_PUBLISH,
  JOB_GET,
  MINE_MONNEY,
  ISSUE_BUY,
  TASK_DETAIL,
  TASK_UPLOAD,
  TASK_MODIFY,
} from "@/api/api.js";
import { fliterKind } from "@/util/util.js";
import header from "@/components/header/header.vue";
import * as imageConversion from "image-conversion";

import {
  Picker,
  Tabbar,
  NoticeBar,
  Dialog,
  TabbarItem,
  Toast,
  Search,
  Swipe,
  SwipeItem,
  Grid,
  GridItem,
  Tab,
  Tabs,
  PullRefresh,
  List,
  Lazyload,
  Sticky,
  Step,
  Steps,
  Form,
  Uploader,
} from "vant";
Vue.use(Tabbar);
Vue.use(TabbarItem);
Vue.use(Swipe);
Vue.use(Search);
Vue.use(SwipeItem);
Vue.use(Grid);
Vue.use(GridItem);
Vue.use(Tab);
Vue.use(Tabs);
Vue.use(PullRefresh);
Vue.use(List);
Vue.use(Lazyload);
Vue.use(Sticky);
Vue.use(VanImage);
Vue.use(NoticeBar);
Vue.use(Step);
Vue.use(Steps);
Vue.use(Form);
Vue.use(Picker);
Vue.use(Dialog);
Vue.use(Toast);
Vue.use(Uploader);

export default {
  name: "taskEdit",
  components: {
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [header.name]: header,
  },
  data() {
    return {
      id: "",
      name: "",
      taskLink: "",
      requirement: "",
      info: "",
      // 选择类型下拉
      list: [],
      showPicker1: false,
      checkName: "",
      type_id: "",
      // 获取数据
      durationList: [],
      issueLevelList: [],
      balance: "",
      verify: "",
      issueRemainTimes: "",
      // 有效时间
      value: "默认",
      showPicker: false,
      columns: [],
      duration: "-1",
      //图片修改
      fileList: [],
      verify_imgs: "",
    };
  },
  mounted() {
    this.getInitData();
    let id = this.$route.query.id;
    this.id = id;
    this.getKind();
    let that = this;
    setTimeout(function () {
      that.getDetail(id);
    }, 100);
  },
  methods: {
    // 校验
    // 	:rules="[{ required: true, message: '请填写任务名称' }]"
    getRule(index) {
      if (index == "") {
        return [
          { index, validator: this.validator, message: "请填写任务名称" },
        ];
      } else if (index.length < 3) {
        return [
          {
            index,
            validator: this.validator,
            message: "任务名称长度需大于3个字节",
          },
        ];
      }
    },
    validator(value, rule) {
      return false;
    },

    async getKind() {
      const { data } = await this.$reqGet(JOB_GET, {});
      if (data.status == 1) {
        let list = JSON.parse(JSON.stringify(data.data));
        let arr = [];
        for (let i = 0; i < list.length; i++) {
          for (let j = 0; j < list[i].sublist.length; j++) {
            arr.push({
              id: list[i].sublist[j]["id"],
              text: list[i].sublist[j]["name"],
            });
          }
        }
        let a = JSON.parse(JSON.stringify(arr));
        this.list = a;
      }
    },
    async getInitData() {
      const { data } = await this.$reqPost(TASK_PUBLISH, {});
      if (data.status == 1) {
        // this.columns = data.data.issueLevelList;
        let dateArr = [];
        dateArr = data.data.durationList;
        console.log(dateArr);
        for (let i = 0; i < dateArr.length; i++) {
          dateArr[i]["text"] = dateArr[i]["value"];
        }

        this.columns = dateArr;
        this.verify = data.data.verify;
        this.balance = data.data.balance;
        this.issueRemainTimes = data.data.issueRemainTimes;
      }
    },
    onConfirm(value) {
      let val = JSON.parse(JSON.stringify(value));
      console.log(val);
      this.value = val.value;
      this.duration = val.key;
      // picker.setColumnValues(1,cities[values[0]]);
      this.showPicker = false;
    },
    onConfirm1(value) {
      let val = JSON.parse(JSON.stringify(value));
      this.checkName = val.text;
      this.type_id = val.id;
      // picker.setColumnValues(1,cities[values[0]]);
      this.showPicker1 = false;
    },
    // onChange(picker, values) {
    // 	picker.setColumnValues(1, cities[values[0]]);
    // },
    justifyImgWidth(e) {
      console.log(e.currentTarget.clientWidth);
      this.Imgheight = e.currentTarget.clientWidth;
      // this.logoWidth = e.currentTarget.clientHeight * 2.75
    },
    async getAmount() {
      const { data } = await this.$reqGet(MINE_MONNEY, {});
      console.log(data);
      if (data.status == 1) {
        let info = data.data;
        this.amountsAll =
          parseFloat(info.withdraw_amount) +
          parseFloat(info.non_withdraw_amount);
      }
    },
    async getDetail(id) {
      const { data } = await this.$reqGet(TASK_DETAIL + "/" + id, {});
      if (data.status == 1) {
        let info = data.data;
        info["src"] = info.verify_imgs[0].url;
        this.info = info;
        this.name = info.name;
        this.taskLink = info.task_link;
        this.checkName = info.checkName;
        this.requirement = info.requirement;
        this.type_id = info.type_id;
        this.value = info.exp_time;
        let src = {
          url: info.verify_imgs[0].url,
        };
        let picArr = [];
        picArr.push(src);
        this.fileList = JSON.parse(JSON.stringify(picArr));
        let datas = this.list;
        console.log(datas);
        for (let i = 0; i < datas.length; i++) {
          if (datas[i].id == info.type_id) {
            this.checkName = datas[i].text;
          }
        }
      } else {
      }
    },
    async onSubmit(values) {
      // 上传文件
      if (this.fileList[0] && !this.fileList[0].file) {
        let datas = {
          type_id: this.type_id,
          name: this.name,
          duration: this.duration,
          requirement: this.requirement,
          task_link: this.taskLink,
        };
        if (datas.duration == "-1") {
          delete datas.duration;
        }
        const { data } = await this.$reqPost(
          TASK_MODIFY + "/" + this.id,
          datas
        );
        if (data.status == 1) {
          let that = this;
          Toast.success({
            message: "修改成功!",
            onClose: function () {
              that.$router.push({ name: "publishList" });
            },
          });
        } else {
          Toast(data.info);
        }

        return;
      }
      if (!this.fileList[0]) {
        Toast("请上传图片！");
        return;
      }

      let a = this.fileList[0].file;
      let param = new FormData();
      param.append("file", a);
      let that = this;
      // let file = JSON.parse(JSON.stringify(this.fileList));
      axios
        .post(`${API_PATH + TASK_UPLOAD}`, param, {
          headers: {
            "Content-Type": "multipart/form-data",
            "auth-token": getLocalStorage("user_token").user_token,
          },
        })
        .then(
          function (res) {
            console.log(res);
            if (res.data.status == 1) {
              that.publish(res.data.data.filename);
            }
          },
          function (response) {}
        );

      // this.$router.push({ name: 'step2' });
    },
    async publish(values) {
      console.log(values + "!!!");
      let datas = {
        type_id: this.type_id,
        name: this.name,
        duration: this.duration,
        requirement: this.requirement,
        task_link: this.taskLink,
        verify_imgs: values,
      };
      if (datas.duration == "-1") {
        delete datas.duration;
      }
      const { data } = await this.$reqPost(TASK_MODIFY + "/" + this.id, datas);
      if (data.status == 1) {
        let that = this;
        Toast.success({
          message: "修改成功!",
          onClose: function () {
            that.$router.push({ name: "publishList" });
          },
        });
      } else {
        Toast(data.info);
      }
    },
    beforeRead(file) {
      // 上传之前校验
      return new Promise((resolve, reject) => {
        // console.log('压缩前', file) // 压缩到400KB,大于400KB的图片都会进行压缩，小于则不会
        console.log("压缩前", file);
        imageConversion.compressAccurately(file, 30).then((res) => {
          // console.log(res)
          res = new File([res], file.name, {
            type: res.type,
            lastModified: Date.now(),
          });
          console.log("压缩后", res);
          resolve(res);
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.hView {
  min-height: 100%;
  background-color: #f5f5f5;

  .bg {
    height: 212rem;
    background: linear-gradient(
      180deg,
      #2f81fe 80%,
      rgba(47, 129, 254, 0) 100%
    );
  }

  .card {
    margin: 24rem;
    border-radius: 20rem;
    overflow: hidden;
    background-color: #fff;
    padding: 24rem;
    position: relative;

    /deep/.van-cell {
      margin: 0;
      padding: 24rem 0;
      .van-cell__title {
        font-size: 28rem;
        font-weight: bold;
        min-width: 140rem;
        text-align: left;
      }

      .van-cell__value {
        font-size: 28rem;
      }
    }

    .upload {
      text-align: left;
      margin-top: 24rem;

      .headerUp {
        font-size: 28rem;
        font-weight: bold;
        color: #646566;
      }

      .uploadCo {
        margin-top: 24rem;
      }
    }
  }

  .btn-box {
    padding: 24rem;
    margin-top: 80rem;
    color: #fff;
    .btn {
      background: linear-gradient(137deg, #2cb1ff 0%, #2f81fe 100%);
      border-radius: 44rem;
      font-size: 36rem;
      font-weight: bold;
      height: 88rem;
      box-shadow: 0px 4rem 12rem rgba(75, 150, 255, 0.3);
    }
  }
}
</style>